package com.jsy.common.util.publicApi.aksk;


import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/data")
    public String getData(@RequestHeader Map<String, String> headers,
                          @RequestParam Map<String, String> queryParams) {
        if (!AkSkAuthenticator.verifyRequest("GET", "/api/data", queryParams, null, headers)) {
            throw new RuntimeException("Invalid signature");
        }
        return "Sensitive data response";
    }

    @PostMapping("/submit")
    public String submitData(@RequestHeader Map<String, String> headers,
                             @RequestParam Map<String, String> queryParams,
                             @RequestBody(required = false) String requestBody) {
        if (!AkSkAuthenticator.verifyRequest("POST", "/api/submit", queryParams, requestBody, headers)) {
            throw new RuntimeException("Invalid signature");
        }
        return "Data processed successfully";
    }

    @PostMapping("/generate-key")
    public Map<String, String> generateKeyPair(HttpServletRequest request) {
        // 注意：此接口需要额外权限控制，不能公开访问
        // 示例：验证管理员身份
        String adminToken = request.getHeader("X-Admin-Token");
        if (!"admin-secret-token".equals(adminToken)) {
            throw new RuntimeException("Access denied");
        }

        // 生成AK/SK对
        Map<String, String> keyPair = AkSkGenerator.generateKeyPair();
        String accessKey = keyPair.get("accessKey");
        String secretKey = keyPair.get("secretKey");

        // 返回结果（注意：实际应用中不应直接返回完整SK，应通过安全渠道分发给用户）
        Map<String, String> result = new HashMap<>();
        result.put("accessKey", accessKey);
        result.put("secretKey", secretKey); // 注意：生产环境中应避免此操作
        return result;
    }
}